package com.banana.springcloud.controller;

import com.banana.springcloud.entity.CommonResult;
import com.banana.springcloud.entity.Payment;
import com.banana.springcloud.loadbalancer.MyLoadBalancer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.net.URI;
import java.util.List;

/**
 * @author layman
 * @description: 消费者controller
 * @date 2021/1/9
 */
@RestController
@Slf4j
@RequestMapping("/consumer/payment")
public class OrderController {

    //private static final String PAYMENT_URL = "http://localhost:8001";
    //服务调用地址
    private static final String PAYMENT_URL = "http://CLOUD-PAYMENT-SERVICE";
    @Resource
    private RestTemplate restTemplate;
    @Resource
    private DiscoveryClient discoveryClient;

    @Resource
    private MyLoadBalancer myLoadBalancer; // 自定义负载均衡策略

    @GetMapping("/create")
    public CommonResult<Payment> create(Payment payment){
        return restTemplate.postForObject(PAYMENT_URL+"/payment/create",payment,CommonResult.class);
    }
    @GetMapping("/get/{id}")
    public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id){
        return restTemplate.getForObject(PAYMENT_URL+"/payment/get/"+id,CommonResult.class);
    }

    @GetMapping("/getForEntity/{id}")
    public CommonResult<Payment> getPaymentForEntity(@PathVariable("id") Long id){
        ResponseEntity<CommonResult> Entity = restTemplate.getForEntity(PAYMENT_URL + "/payment/get/" + id, CommonResult.class);
        if(Entity.getStatusCode().is2xxSuccessful()){
            log.info(Entity.toString());
            return Entity.getBody();
        }
        return new CommonResult<>(444,"查询失败");
    }
    @GetMapping("/LoadBalancer")
    public String discovery(){
        //获取对应名称的所有server数量
        List<ServiceInstance> instances = discoveryClient.getInstances("cloud-payment-service");
        if(instances ==null || instances.size() <=0){
            return null;
        }
        ServiceInstance server = myLoadBalancer.getInstance(instances);
        URI uri = server.getUri();
        String object = restTemplate.getForObject(uri + "/payment/LoadBalancer", String.class);
        return object;
    }
}
